package org.seedltd.upms.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 本地锁
 * 
 * @author laizuan
 * @version 1.0
 * @since 2021/10/15 23:08
 */
public class LocalLock {

    private volatile static Map<String, ReentrantLock> LOCK_MAP = new ConcurrentHashMap<>(128);
    public static void lock(String key) {
        ReentrantLock lock = getReentrantLock(key);
        lock.lock();
    }

    public static boolean lock(String key, long timeout, TimeUnit timeUnit) {
        ReentrantLock lock = getReentrantLock(key);
        try {
            return lock.tryLock(timeout, timeUnit);
        } catch (InterruptedException e) {
            LOCK_MAP.remove(key);
            return false;
        }
    }

    private static ReentrantLock getReentrantLock(String key) {
        ReentrantLock lock = LOCK_MAP.get(key);
        if (lock == null) {
            ReentrantLock reentrantLock = new ReentrantLock();
            lock = LOCK_MAP.putIfAbsent(key, reentrantLock);
        }
        return lock;
    }

    public static void unlock(String key) {
        ReentrantLock lock = LOCK_MAP.get(key);
        if (lock != null) {
            LOCK_MAP.remove(key);
            lock.unlock();
        }
    }

}
